export default class NodePool {

    public static mPool = {};

    /**
     * 批量初始化对象池 
     * @param thisO 
     * @param objArray 
     */
    public static batchInitObjPool(thisO: object, objArray: ObjPoolInfo[]): void {
        for (var i = 0; i < objArray.length; i++) {
            var objinfo = objArray[i];
            this.initObjPool(thisO, objinfo);
        }
    }

    /**
     * 初始化对象池
     * @param thisO 
     * @param objInfo 
     * @param callback 
     */
    public static initObjPool(thisO: object, objInfo: ObjPoolInfo, callback: Function = null): void {
        var name = objInfo.name;
        var poolName = name + 'Pool';
        thisO[poolName] = new cc.NodePool();
        let initPollCount = objInfo.initPollCount;
        for (let ii = 0; ii < initPollCount; ++ii) {
            let nodeO = cc.instantiate(objInfo.prefab); // 创建节点
            thisO[poolName].put(nodeO); // 通过 putInPool 接口放入对象池
        }
        callback && callback();
    }

    /**
     * 生成节点
     * @param pool 
     * @param prefab 
     * @param nodeParent 
     * @returns 
     */
    public static getNewNode(pool: cc.NodePool, prefab: cc.Prefab, nodeParent: cc.Node = null): any {
        let newNode = null;
        if (pool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象
            newNode = pool.get();
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建
            newNode = cc.instantiate(prefab);
            // pool.put(newNode);
        }
        nodeParent && nodeParent.addChild(newNode);
        return newNode;
    }

    /**
     * 放回对象池
     * @param thisO 
     * @param nodeinfo 
     */
    public static backObjPool(thisO: object, nodeinfo: ObjPoolInfo): void {
        var poolName = nodeinfo.name + 'Pool';
        if (thisO[poolName]) {
            thisO[poolName].put(nodeinfo.prefab);
        } else {

        }
    }

    /**
     * 清理对象池
     * @param thisO 
     * @param nodeinfo 
     */
    public static clearPool(thisO: object, nodeinfo: ObjPoolInfo): void {
        var poolName = nodeinfo.name + 'Pool';
        thisO[poolName].clear();
    }
}

/**
 * 对象池数据
 * @param name 名称
 * @param initPollCount 初始化数量
 * @param prefab 预制物或节点
 */
export interface ObjPoolInfo {
    name: string;
    initPollCount?: number;
    prefab: cc.Prefab | cc.Node;
}